<?php

namespace app\callback\controller;

use app\admin\model\base\UserSubscribeLog;
use app\Request;
use platform\MaYouPlatform;
use redis\RedisTools;
use think\facade\Db;
use think\facade\Log;

class MaYou
{
    /**
     * 接收回调信息
     * @param Request $request
     */
    public function MaYouAfterNotify(Request $request): string
    {
        $post_data = $request->all();
        Log::write($post_data);
        if (!$post_data) {
            $post_data = $request->all();
        }
        //验证签名
        $sign = md5($post_data['appid'].$post_data['openid'].$post_data['time'].MaYouPlatform::$key);
//        if($sign != $post_data['sign']){
//            Log::write('码友回调签名错误');
//            return 'error';
//        }
        $response_message = $post_data['state'];
        $key = 'my:'.$response_message;
        //验证是否正确的响应
        $oRedis = RedisTools::getInstance(config('cache.stores.redis'), 0)->getRedis();
        $uid = $oRedis->get($key);
        if(!$uid){
            Log::write('码友回调用户不存在');
            return 'error';
        }
        //查询用户
        $user_id = 0;
        $user = Db::name('user')->where('unionid','=',$uid)->find();
        if($user) $user_id = $user['id'];
        $post_data = is_array($post_data) ? $post_data : json_decode($post_data, true);
        UserSubscribeLog::oneLogSave($user_id,$post_data['appid'],$post_data['status'] != 1 ? 0 : 1,$post_data['appid'],19);
        $oRedis->del($key);
        return 'success';
    }
}